﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;

namespace PengSW.HeartBeat
{
    public class HeartBeatServiceHost : IDisposable
    {
        public HeartBeatServiceHost(string aServiceName, int aPort = 808)
        {
            ServiceName = aServiceName;
            Port = aPort;
        }

        private ServiceHost m_ServiceHost = null;
        public string ServiceName { get; private set; }
        public int Port { get; private set; }

        public void StartService()
        {
            m_ServiceHost = new ServiceHost(typeof(HeartBeatService));
            m_ServiceHost.AddServiceEndpoint(typeof(IHeartBeatService), new NetTcpBinding(), string.Format(@"net.tcp://localhost:{0}/{1}", Port, ServiceName));
            m_ServiceHost.Open();
        }

        public void StopService()
        {
            if (m_ServiceHost == null) return;
            m_ServiceHost.Close();
            (m_ServiceHost as IDisposable).Dispose();
            m_ServiceHost = null;
        }

        public bool ServiceIsRunning
        {
            get { return m_ServiceHost != null && m_ServiceHost.State == CommunicationState.Opened; }
        }

        public void Dispose()
        {
            StopService();
        }
    }
}
